package cn.hj.basic.service.impl;


import cn.hj.basic.constant.BaseConstant;
import cn.hj.basic.exception.BusinessException;
import cn.hj.basic.service.IVerifyCodeService;
import cn.hj.basic.util.SmsUtil;
import cn.hj.basic.util.StrUtils;
import cn.hj.user.domain.User;
import cn.hj.user.mapper.LogininfoMapper;
import cn.hj.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.util.SystemPropertyUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public void sendSmsCode(Map<String,String> params) {
        String phone = params.get("phone");
        String type = params.get("type");

        //1.手机号不能为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)) {
            throw new BusinessException("手机号不能为空");
        }
        String businessKey = "";
        //type为register说明是注册
        if (type.equals("register")) {
            //查询手机号是否已注册
            User user = userMapper.loadByPhone(phone);
            //如果已经被注册，告知登录
            if (user != null) {
                throw new BusinessException("手机号已被注册，请直接登录");
            }
            businessKey = BaseConstant.BUSINESS_REGISTER + phone;
            //type为binder说明是绑定
        } else if (type.equals("binder")) {
            businessKey = BaseConstant.BUSINESS_binder_REGISTER + phone;
        }
            sendCode(businessKey);
    }
        public void sendCode(String businessKey){
            //如果手机号没有注册过，判断是否过了登录时间
            String str = businessKey;
            Object codeVuleTmp = redisTemplate.opsForValue().get(str);
            String code = null;
            if(codeVuleTmp!=null){
                //如果时间小于1分钟，开骂
                Long oldTime = Long.valueOf(((String) codeVuleTmp).split(":")[1]);
                if (System.currentTimeMillis()-oldTime<1*60*1000){
                    throw new BusinessException("facker you mather");
                }
                //如果时间大于1分钟，并且小于3分钟使用原来的验证码
                code = ((String) codeVuleTmp).split(":")[0];
            }else {
                //是一次来，或者是时间过期了，重新生成验证码
                code = StrUtils.getComplexRandomString(4);
            }
            //将验证码保存到redis设置3分钟过期
            String codeValue = code + ":" + System.currentTimeMillis();
            redisTemplate.opsForValue().set(str,codeValue,3, TimeUnit.MINUTES);
            System.out.println(code);
            /*//调用工具类发送短信验证码
            SmsUtil.sendSms(phone,"你好你的验证码为"+code+"请在3分钟内使用");*/
            }
    }


